/**
 * @author 
 * @time 
 * @description pinia持久化存储
 */

import { createPinia, defineStore } from 'pinia';
import { deCode, enCode } from '../utils'

/**创建一个pinia全局实例对象 */
const Pinia = createPinia()
let token = sessionStorage.getItem('xingqiu-token')
let userInfo = sessionStorage.getItem('xingqiu-userinfo') || {}
let userRights = sessionStorage.getItem('xingqiu-userrights') || {}
const commonDefinition = defineStore(
    // 必须加有一个id名
    'common',
    {
        state() {
            return {
                token: token,
                userInfo,
                userRights
            }
        },
        /**定义getters获取数据 */
        getters: {
            getToken() {
                return deCode(this.token)
            },
            getUserInfo() {
                return JSON.parse(deCode(this.userInfo))
            },
            getUserRights() {
                return JSON.parse(deCode(this.userRights))
            }
        },
        /**赋值方法--actions */
        actions:{
            setToken(_token) {
                _token = enCode(_token)
                this.token = _token
                sessionStorage.setItem('xingqiu-token', _token)
            },
            setUserInfo(_userInfo) {
                _userInfo = enCode(JSON.stringify(_userInfo))
                this.userInfo = _userInfo
                sessionStorage.setItem('xingqiu-userinfo', _userInfo)
            },
            setUserRights(_userRights) {
                // debugger
                _userRights = enCode(JSON.stringify(_userRights))
                this.userRights = _userRights
                sessionStorage.setItem('xingqiu-userrights', _userRights)
            }
        }

    }
)

/**到处定义的pinia实例和定义的各个状态数据仓对象 */
export {
    Pinia,
    commonDefinition
}
